const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');

// 未捕获的异常处理
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err);
  console.error(err.stack);
});

// 未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的Promise拒绝:', reason);
});

const app = express();
const PORT = process.env.PORT || 1497;

// 中间件
app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../frontend/dist')));

// 创建数据库目录（如果不存在）
const dbDir = path.join(__dirname, '../database');
const eventsDir = path.join(dbDir, 'events');
const categoriesDir = path.join(dbDir, 'categories');
const logsDir = path.join(dbDir, 'logs');
const variablesDir = path.join(dbDir, 'variables');
const dataDir = path.join(__dirname, 'data'); // 自定义节点类型数据目录

try {
  [dbDir, eventsDir, categoriesDir, logsDir, variablesDir, dataDir].forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`创建目录: ${dir}`);
    }
  });
} catch (error) {
  console.error('创建数据目录失败:', error);
}

// 导入路由
let eventRoutes, categoryRoutes, logRoutes, variableRoutes, customNodeTypeRoutes;

try {
  eventRoutes = require('./routes/events');
  categoryRoutes = require('./routes/categories');
  logRoutes = require('./routes/logs');
  variableRoutes = require('./routes/variables');
  customNodeTypeRoutes = require('./routes/customNodeTypeRoutes');
  console.log('所有路由模块加载成功');
} catch (error) {
  console.error('路由模块加载失败:', error);
}

// 使用路由
try {
  app.use('/api', eventRoutes);
  app.use('/api', categoryRoutes);
  app.use('/api', logRoutes);
  app.use('/api', variableRoutes);
  app.use('/api', customNodeTypeRoutes);
  console.log('所有路由注册成功');
} catch (error) {
  console.error('路由注册失败:', error);
}

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: '服务器正常运行' });
});

// 处理前端路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('应用错误:', err.stack);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
const server = app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 处理服务器错误
server.on('error', (error) => {
  if (error.code === 'EADDRINUSE') {
    console.error(`端口 ${PORT} 已被占用，请尝试其他端口`);
  } else {
    console.error('服务器启动错误:', error);
  }
}); 